package com.ssdp.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ssdp.dto.*;
import com.ssdp.entity.User;
import com.ssdp.entity.UserInfo;
import com.ssdp.service.IUserInfoService;
import com.ssdp.service.IUserService;
import com.ssdp.utils.PasswordEncoder;
import com.ssdp.utils.RegexUtils;
import com.ssdp.utils.UserHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

/**
 * @author syo 2319615164@qq.com
 * @description 用户接口
 * @date 2024/3/14
 * @Copyright syo
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关接口")
@RequiredArgsConstructor
public class UserController {

    private final Logger logger = LoggerFactory.getLogger(UserController.class);

    private final IUserService userService;

    private final IUserInfoService userInfoService;

    ////////////////// 用户管理接口 //////////////////
    @ApiOperation("新增用户")
    @PostMapping("/add")
    public Result addUser(@RequestBody UserAddDTO userAddDTO) {
        boolean res = userAddDTO != null && !RegexUtils.isPhoneInvalid(userAddDTO.getPhone());

        if (!res) {
            logger.error("添加用户失败!");
            throw new RuntimeException("添加用户失败!");
        }

        User user = BeanUtil.toBean(userAddDTO, User.class);
        res = userService.save(user);

        if (!res) {
            logger.error("添加用户失败!");
            throw new RuntimeException("添加用户失败!");
        }

        return Result.ok();
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/delete")
    public Result deleteUser(@RequestParam("phone") String phone) {
        boolean res = !RegexUtils.isPhoneInvalid(phone);

        if (!res) {
            logger.error("删除用户失败!");
            throw new RuntimeException("删除用户失败!");
        }

        res = userService
                .remove(new LambdaQueryWrapper<User>()
                        .eq(User::getPhone, phone));

        if (!res) {
            logger.error("删除用户失败!");
            throw new RuntimeException("删除用户失败!");
        }

        return Result.ok();
    }

    @ApiOperation("修改用户")
    @PutMapping("/update")
    public Result updateUser(@RequestBody UserUpdateDTO userUpdateDTO) {
        boolean res = userUpdateDTO != null && !RegexUtils.isPhoneInvalid(userUpdateDTO.getPhone());

        if (!res) {
            logger.error("修改用户失败!");
            throw new RuntimeException("修改用户失败!");
        }

        User user = BeanUtil.toBean(userUpdateDTO, User.class);
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(PasswordEncoder.encode(user.getPassword()));
        }
        res = userService.update(user, new LambdaQueryWrapper<User>().eq(User::getPhone,
                user.getPhone()));

        if (!res) {
            logger.error("修改用户失败!");
            throw new RuntimeException("修改用户失败!");
        }

        return Result.ok();
    }

    ////////////////// 用户登陆登出接口 //////////////////
    @ApiOperation("发送验证码")
    @PostMapping("/code")
    public Result sendCode(@RequestParam("phone") String phone) {
        return userService.sendCode(phone, null);
    }

    @ApiOperation("用户登陆")
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm){
        return userService.login(loginForm, null);
    }

    @ApiOperation("用户登出")
    @PostMapping("/logout")
    @ApiImplicitParam(value = "authorization", required = true, paramType = "header")
    public Result logout(){
        userService.logout();
        return Result.ok();
    }

    @ApiOperation("获取当前登陆用户信息")
    @GetMapping("/me")
    @ApiImplicitParam(name = "token", value = "authorization", required = true, paramType = "header")
    public Result me(){
        UserDTO user = UserHolder.getUser();

        if(user == null){
            return Result.fail("当前未登陆！");
        }
        return Result.ok(user);
    }

    ////////////////// 用户相关信息查询接口 //////////////////
    @ApiOperation("根据Id查询用户信息")
    @GetMapping("/info/{id}")
    @ApiImplicitParam(name = "token", value = "authorization", required = true, paramType = "header")
    public Result info(@PathVariable("id") Long userId){
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        return Result.ok(info);
    }

    @ApiOperation("根据用户Id查询用户信息")
    @GetMapping("/{id}")
    @ApiImplicitParam(name = "token", value = "authorization", required = true, paramType = "header")
    public Result queryUserById(@PathVariable("id") Long userId){
        User user = userService.getById(userId);
        if (user == null) {
            return Result.fail("用户不存在！");
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return Result.ok(userDTO);
    }


    ////////////////// 用户签到接口 //////////////////
    @ApiOperation("用户签到")
    @PostMapping("/sign")
    @ApiImplicitParam(name = "token", value = "authorization", required = true, paramType = "header")
    public Result sign() {
       return userService.sign();
    }

    @ApiOperation("用户累计签到")
    @GetMapping("/sign/count")
    @ApiImplicitParam(name = "token", value = "authorization", required = true, paramType = "header")
    public Result signCount() {
        return userService.signCount();
    }
}
